package com.ruoyi.app.service.impl

import cn.hutool.core.bean.BeanUtil
import cn.hutool.http.HttpUtil
import com.alibaba.fastjson.JSON
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.ruoyi.app.common.Data
import com.ruoyi.app.common.Fail
import com.ruoyi.app.common.Ok
import com.ruoyi.app.domain.dto.AdvertisingSettingDto
import com.ruoyi.app.domain.vo.*
import com.ruoyi.app.service.IndexApiService
import com.ruoyi.back.domain.*
import com.ruoyi.back.domain.v3.ExtractVideo
import com.ruoyi.back.enums.AdvertisingTypeEnum
import com.ruoyi.back.service.*
import com.ruoyi.back.service.impl.AdvertisingSettingService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.regex.Pattern

@Service
class IndexApiServiceImpl : IndexApiService {

    @Autowired
    private lateinit var advertisingService: OpenAdvertisingService

    @Autowired
    private lateinit var advertisingSettingService: AdvertisingSettingService

    @Autowired
    private lateinit var functionService: FunctionService

    @Autowired
    private lateinit var channelManagerService: ChannelManagerService

    @Autowired
    private lateinit var spreadCenterSettingService: SpreadCenterSettingService

    @Autowired
    private lateinit var wxPaySettingService: WxPaySettingService

    @Autowired
    private lateinit var aliPaySettingService: AliPaySettingService

    @Autowired
    private lateinit var channelFunctionService: ChannelFunctionService

    @Autowired
    private lateinit var extractVideoService: ExtractVideoService

    @Autowired
    private lateinit var userChannelFunctionService: UserChannelFunctionService

    private val log: Logger = LoggerFactory.getLogger(IndexApiServiceImpl::class.java)

    override fun indexData(channelCode: String?): Data<IndexVo> =
        Ok("获取首页数据成功", IndexVo().apply {
            banner = advertisingService.list(
                KtQueryWrapper(OpenAdvertising::class.java)
                    .eq(OpenAdvertising::advertisingType, AdvertisingTypeEnum.BANNER.code)
                    .eq(OpenAdvertising::isShow, true)
                    .orderByDesc(OpenAdvertising::createTime)
            )
                .takeIf { it.isNotEmpty() }
                ?.run {
                    map {
                        AdvertisingVo().apply { BeanUtil.copyProperties(it, this) }
                    }
                }
            function = // 针对老用户
                (channelManagerService.getOne(
                    KtQueryWrapper(ChannelManager::class.java)
                        .eq(ChannelManager::code, channelCode)
                )?.id?.run {
                    channelFunctionService.getFunctionByChannel(this)
                } ?: emptyList())
                    .takeIf { it.isNotEmpty() }
                    ?.run {
                        map {
                            FunctionVo().apply {
                                functionService.getById(it.functionId)?.let {
                                    BeanUtil.copyProperties(it, this)
                                }
                                delay = it.delay
                            }
                        }
                    }
//            } ?: run {
//               (channelManagerService.getOne(
//                    KtQueryWrapper(ChannelManager::class.java)
//                        .eq(ChannelManager::code, channelCode)
//                )?.id?.run {
//                    channelFunctionService.getFunctionByChannel(this)
//                } ?: emptyList())
//                    .takeIf { it.isNotEmpty() }
//                    ?.run {
//                        functionService.list(
//                            KtQueryWrapper(Function::class.java)
//                                .`in`(Function::id, map { it.functionId })
//                                .orderByAsc(Function::orderNum)
//                        )
//                            .takeIf { it.isNotEmpty() }
//                            ?.run {
//                                map {
//                                    FunctionVo().apply {
//                                        BeanUtil.copyProperties(it, this)
//                                    }
//                                }
//                            }
//                    }
//           // }
//        }
        })

    override fun getAdvertisingSetting(advertisingSettingDto: AdvertisingSettingDto): Data<AdvertisingSettingVo> =
        Ok("获取广告配置参数成功", advertisingSettingService.getOne(KtQueryWrapper(AdvertisingSetting::class.java)
            .eq(AdvertisingSetting::advertisingType, advertisingSettingDto.advertisingType))
            ?.let {
                AdvertisingSettingVo().apply {
                    BeanUtil.copyProperties(it, this)
                }
            } ?: AdvertisingSettingVo())

    override fun getGlobalSetting(): Data<GlobalSetting> =
        Ok("获取全局配置参数成功", GlobalSetting().apply {
            spreadCenterSettingService.getOne(
                KtQueryWrapper(SpreadCenterSetting::class.java)
            )?.let {
                BeanUtil.copyProperties(it, this)
            }

            wxPaySettingService.getOne(KtQueryWrapper(WxPaySetting::class.java))
                ?.let {
                    wxPayIcon = it.isUse ?: false
                }

            aliPaySettingService.getOne(KtQueryWrapper(AliPaySetting::class.java))
                ?.let {
                    aliPayIcon = it.isUse ?: false
                }
        })

    override fun resolveVideo(urlText: String): Data<List<VideoVo>> =
        urlText.urls().takeIf { it.isNotEmpty() }
            ?.run {
                Ok("提取短视频成功", mapNotNull {
                    JSON.parseObject(HttpUtil.post(it.api(), it.map())).let { jsonObject ->
                        if (jsonObject.getIntValue("code") == 200) {
                            jsonObject.getJSONObject("data").let { data ->
                                VideoVo().apply {
                                    title = data.getString("title")
                                    cover = data.getString("cover")
                                    url = data.getString("url")
                                }
                            }
                        } else {
                            log.error("$it 的链接提取短视频失败!")
                            null
                        }
                    }
                })
            } ?: Fail("暂时没有提取出来相关链接!")

    override fun extractVideoTemplate(): Data<List<ExtractVideo>> =
        Ok("获取体验提取短视频模板成功", extractVideoService.list(KtQueryWrapper(ExtractVideo::class.java)
            .orderByDesc(ExtractVideo::createTime)))

    fun String.api() = "https://tenapi.cn/v2/video"
    fun String.map() = mapOf("url" to this)
    fun String.urls(): List<String> =
        Pattern.compile("(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]")
            .let { pattern ->
                val urls = arrayListOf<String>()
                pattern.matcher(this).let { matcher ->
                    while (matcher.find()) {
                        urls.add(matcher.group())
                    }
                }
                urls
            }

}